﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WorkflowCoreDockingDemo.Workflows
{
    public class WorkflowAdapter
    {
        private readonly IHttpClientFactory  httpClientFactory;
        private readonly IConfiguration _configuration;
        private readonly Microsoft.Extensions.Logging.ILogger<WorkflowAdapter> logger;

        public WorkflowAdapter(IHttpClientFactory httpClientFactory, IConfiguration configuration, Microsoft.Extensions.Logging.ILogger<WorkflowAdapter> logger)
        {
            this.httpClientFactory = httpClientFactory;
            _configuration = configuration;
            this.logger = logger;
        }

        /// <summary>
        /// 根据实体类型获取所有的处理中的工作流
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<WorkTask>> GetAllProcessingWorkTasksByEntityType(string entityFullName, params string[] entityKeyValues)
        {
            try
            {
                var workflowHost = _configuration.GetValueFromManyChanels("WorkFlowHost");
                //workflowHost = "http://localhost:5000/";
                var url = $"{workflowHost.TrimEnd('/')}/api/workflow/GetAllProcessingWorkTasksByEntityType?EntityFullName={entityFullName}&{string.Join("&", entityKeyValues.Select(v => $"EntityKeyValues={v}"))}";
                var httpClient = httpClientFactory.CreateClient();

                var result = await httpClient.GetStringAsync(url);
                var jObj = JObject.Parse(result);

                return JsonConvert.DeserializeObject<List<WorkTask>>(jObj["data"].ToString());
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
                //
                return new List<WorkTask>();
            }
        }
    }
}
